import 'dart:async';
import 'dart:io';

import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:system_tray/system_tray.dart';
import 'package:timezone/timezone.dart' as tz;

import 'windows.dart' as windows;

class SystemTrayService {
  final SystemTray _systemTray = SystemTray();
  final StreamController<String> _notificationController =
      StreamController.broadcast();
  late final FlutterLocalNotificationsPlugin? _flutterLocalNotificationsPlugin;

  Stream<String> get onNotificationClicked => _notificationController.stream;

  SystemTrayService() {
    if (Platform.isWindows) {
      _flutterLocalNotificationsPlugin = null;
    } else {
      _flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
    }
  }

  Future<void> initSystemTray() async {
    final String path = 'assets/icons/tray_icon.png';

    await _initNotifications();
  }

  Future<void> _initNotifications() async {
    if (_flutterLocalNotificationsPlugin == null) return;

    const AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    const InitializationSettings initializationSettings =
        InitializationSettings(
      android: initializationSettingsAndroid,
      windows: windows.initSettings,
    );

    await _flutterLocalNotificationsPlugin!.initialize(
      initializationSettings,
      onDidReceiveNotificationResponse: (NotificationResponse response) {
        _notificationController.add(response.payload ?? '');
      },
    );
  }

  Future<void> showNotification(String message) async {
    await _systemTray.setToolTip(message);
  }

  Future<void> scheduleNotification({
    required int id,
    required String title,
    required String body,
    required tz.TZDateTime scheduledDate,
    required Duration repeatInterval,
    String? payload,
  }) async {
    if (Platform.isWindows) {
      // Windows平台使用系统托盘通知
      await _systemTray.setToolTip('$title: $body');
      _notificationController.add(payload ?? '');
    } else {
      // 其他平台使用flutter_local_notifications
      if (_flutterLocalNotificationsPlugin == null) return;

      const AndroidNotificationDetails androidPlatformChannelSpecifics =
          AndroidNotificationDetails(
        'your_channel_id',
        '你的通知频道',
        channelDescription: '用于合同管理系统的通知',
        importance: Importance.max,
        priority: Priority.high,
      );

      const NotificationDetails platformChannelSpecifics = NotificationDetails(
        android: androidPlatformChannelSpecifics,
      );

      await _flutterLocalNotificationsPlugin!.zonedSchedule(
        id,
        title,
        body,
        scheduledDate,
        platformChannelSpecifics,
        androidScheduleMode: AndroidScheduleMode.exactAllowWhileIdle,
        matchDateTimeComponents: DateTimeComponents.time,
        payload: payload,
      );
    }
  }
}
